package hanelsoft.vn.dictionaylearn.control.service;

import hanelsoft.vn.dictionaylearn.R;
import hanelsoft.vn.dictionaylearn.control.activity.StartContentViewFromWidget;

import java.io.File;
import java.io.IOException;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Environment;
import android.text.Html;
import android.util.Log;
import android.widget.RemoteViews;

public class WidgetMyProvider extends AppWidgetProvider{
	String tag = "[WidgetMyProvider]", wordWidget;
	RemoteViews remoteViews;
	ComponentName mComponentName;
	SharedPreferences shareWidget, sharePlaySound, prefs;
	MediaPlayer mp;
	@Override
	  public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		ComponentName thisWidget = new ComponentName(context, WidgetMyProvider.class);
	    int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
	    for (int widgetId : allWidgetIds) {
            appWidgetManager.updateAppWidget(widgetId, remoteViews);
	    }
	  }
	 
	private PendingIntent runActivityContent(Context context) {
		shareWidget = context.getSharedPreferences("ShareWidget", 0);
		shareWidget.edit().putString("word_widget", wordWidget).commit();
		Intent i = new Intent(context, StartContentViewFromWidget.class);
		return PendingIntent.getActivity(context, 0, i, 0);
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		  Log.i(tag, "onReceive");
		  if(intent.getAction().equals(AppWidgetManager.ACTION_APPWIDGET_UPDATE))
		  {
			Log.i(tag, "run shareWidget");
			sharePlaySound = context.getSharedPreferences("CBplaysound", 1);
			shareWidget = context.getSharedPreferences("ShareWidget", 0);
			Log.i(tag, "run remoteViews");
			remoteViews = new RemoteViews(context.getPackageName(), R.layout.vocabulary_widget);
			wordWidget = shareWidget.getString("WidgetMyWidgetProvider_word", "");
			String contentWidget = shareWidget.getString("WidgetMyWidgetProvider_content", "");
			//contentWidget = formatContent(contentWidget);
			Log.i(tag, "run contentWidget: "+contentWidget);
		    remoteViews.setTextViewText(R.id.vocabulary_widget_Content, Html.fromHtml(contentWidget));
			remoteViews.setTextColor(R.id.vocabulary_widget_Content, Color.WHITE);
			remoteViews.setOnClickPendingIntent(R.id.vocabulary_widget_Content, runActivityContent(context));
			//
			Log.i(tag, "run show sound: "+wordWidget);
			showSound(wordWidget, context);
			Log.i(tag, "run startContent: "+wordWidget);
			ComponentName myWidget = new ComponentName(context, WidgetMyProvider.class);
		    AppWidgetManager manager = AppWidgetManager.getInstance(context);
		    manager.updateAppWidget(myWidget, remoteViews);	
		  }
//		  if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
//		  {
//			  AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); 
//			  RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.vocabulary_widget);
//			  ComponentName thisWidget = new ComponentName(context, WidgetMyProvider.class);
//			  remoteViews.removeAllViews(R.id.vocabulary_widget_Sound);
//			  remoteViews.removeAllViews(R.id.vocabulary_widget_Content);
//			  appWidgetManager.updateAppWidget(thisWidget, remoteViews);
//		  }
		super.onReceive(context, intent);
	}

	//
	public String formatContent(String content)
    {
		StringBuilder htmlData = new StringBuilder();
		String mContentStyle = shareWidget.getString("style", "");
		htmlData.append("<html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>\n");
		if (mContentStyle != null && !mContentStyle.equals(""))
		{
			htmlData.append("<head><style type=\"text/css\">"+mContentStyle+"</style></head>\n");
		}
		htmlData.append("<body><font face=\"Times New Roman\" size=\"4\">");
		htmlData.append(content);
		htmlData.append("</font></body></html>");
		return htmlData.toString();
    }
    public void showSound(String mCurrentWord, Context context)
    {
    	String mSourcesound = shareWidget.getString("sourcesound", "");
    	Log.i(tag, "mSourcesound: "+mSourcesound);
    	remoteViews.setImageViewResource(R.id.vocabulary_widget_Sound, R.drawable.bg_params);
    	String soundPath = shareWidget.getString("soundPath", "");
    	Log.i(tag, "soundPath: "+soundPath);
    	String soundPathNotSDCard = shareWidget.getString("soundPathNotSDCard", "");
    	Log.i(tag, "soundPathNotSDCard: "+soundPathNotSDCard);
    	final String fullPathFilePro;
    	if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
    		fullPathFilePro = soundPath + mSourcesound + "/" + mCurrentWord + ".wav";
        }
        else
        {
        	fullPathFilePro = soundPathNotSDCard + mSourcesound + "/" + mCurrentWord + ".wav";
        }
    	Log.i(tag, "fullPathFilePro: "+fullPathFilePro);
		File f = new File(fullPathFilePro);
		if (f.exists())
		{
			Log.i(tag, "File exists: "+f);
			remoteViews.setImageViewResource(R.id.vocabulary_widget_Sound, R.drawable.icon_sound);
			remoteViews.setOnClickPendingIntent(R.id.vocabulary_widget_Sound, runSoundWidget(context));
			mp = new MediaPlayer();
			try {
				shareWidget.edit().putString("fullPathFilePro",fullPathFilePro).commit();
				mp.setDataSource(fullPathFilePro);
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				mp.prepare();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			mp.setLooping(false);
			mp.setVolume(1.0f, 1.0f);
			if(sharePlaySound.getInt("playsound", 0) == 1)
			{
				if(mp.isPlaying() == false)
				{
					mp.start();
				}
				else
				{
					mp.stop();
					mp.start();
				}
			}
		}
    }

	private PendingIntent runSoundWidget(Context context) {
		Log.i(tag, "runSoundWidget");
		Intent intent = new Intent();
	    intent.setAction("hanelsoft.vn.dictionaylearn.control.service.WIDGET_LEARN");
	    return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
	}
} 

